package com.sqs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.sqs.constant.ExceptionConstant;
import com.sqs.context.BaseContext;
import com.sqs.dto.RepositoryUpdateDTO;
import com.sqs.entity.Repository;
import com.sqs.exception.RepositoryNotFoundException;
import com.sqs.mapper.RepositoryMapper;
import com.sqs.service.IRepositoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqs.vo.RepositoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class RepositoryServiceImpl extends ServiceImpl<RepositoryMapper, Repository> implements IRepositoryService {

    @Autowired
    private RepositoryMapper repositoryMapper;

    /**
     * 新增知识库
     * @param name
     * @return
     * */
    public RepositoryVO repositoryInsert(String name) {
        Repository repository = Repository.builder()
                .userId(BaseContext.getCurrentId())
                .name(name)
                .build();
        save(repository);
        return BeanUtil.copyProperties(repository, RepositoryVO.class);
    }

    /**
     * 查询该用户所有的知识库
     * @return
     */
    public List<RepositoryVO> repositoriesSelect() {
        List<Repository> repositories = lambdaQuery()
                .eq(Repository::getUserId, BaseContext.getCurrentId())
                .orderByDesc(Repository::getCreateTime)
                .list();
        return BeanUtil.copyToList(repositories, RepositoryVO.class);
    }

    /**
     * 修改知识库信息
     * @param repositoryUpdateDTO
     * @return
     * */
    public void repositoryUpdate(RepositoryUpdateDTO repositoryUpdateDTO) {
        //1.查询数据库是否存在
        if(!lambdaQuery().eq(Repository::getId, repositoryUpdateDTO.getId()).exists()){
            throw new RepositoryNotFoundException(ExceptionConstant.REPOSITORY_NOT_FOUND);
        }
        //2.修改
        Repository repository = Repository.builder()
                .id(repositoryUpdateDTO.getId())
                .name(repositoryUpdateDTO.getName())
                .updateTime(LocalDateTime.now())
                .build();
        updateById(repository);
    }

    /**
     * 删除知识库
     * @param id
     * @return
     * */
    public void repositoryDelete(Long id) {
        //1.查询数据库是否存在
        if(!lambdaQuery().eq(Repository::getId, id).exists()){
            throw new RepositoryNotFoundException(ExceptionConstant.REPOSITORY_NOT_FOUND);
        }
        removeById(id);
    }


}
